using System;
using System.Collections.Generic;
using System.Text;
using Calc.Execution;

namespace Calc.UI.Console
{
	public class Program
	{
		static int Main(string[] args)
		{
			string statement = "";

			ExecutionEngine engine = new ExecutionEngine();

			ExecutionResult result = null;

			// re-combine the command line arguments
			if ( args.Length > 0 )
			{

				StringBuilder sb = new StringBuilder(args.Length);

				bool first = true;

				foreach ( string arg in args )
				{
					if ( first )
						first = false;
					else
						sb.Append(" ");
					sb.Append(arg);
				}
				statement = sb.ToString();

				result = engine.ExecuteExclusiveLine(statement);

				if ( result.Result == ExecutionType.Error )
				{
					System.Console.WriteLine(result.Statement);
					System.Console.WriteLine(result.Message);

					return 1;
				}

				if ( result.Result == ExecutionType.Eval )
				{
					System.Console.WriteLine(result.Value.ToString());
					return 0;
				}
			}
			else
			{
				statement = System.Console.ReadLine();

				while ( statement.Trim() != "")
				{
					result = engine.ExecuteLine(statement);

					if ( result.Result == ExecutionType.Error )
					{
						System.Console.WriteLine(result.Statement);
						System.Console.WriteLine(result.Message);
					}

					if ( result.Result == ExecutionType.Eval )
					{
						System.Console.WriteLine(result.Value.ToString());
					}


					statement = System.Console.ReadLine();
				}
			}

			return 0;
		}
	}
}
